iT邦幫忙

2022 iThome 鐵人賽

DAY 3
0
自我挑戰組

30天 Neetcode解題之路系列 第 3

Day 3 - 242. Valid Anagram

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~


Question

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Think

判斷s是否可以重新組合出t這個字。

想法是把s跟t分別拆解,用dictionary存每個字母出現次數,如果兩者一樣,就代表OK~

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        dict_s = {}
        dict_t = {}
        
        for index in range(len(s)):
            if s[index] in dict_s:
                dict_s[s[index]] += 1
            else:
                dict_s[s[index]] = 1
                
        for index in range(len(t)):    
            if t[index] in dict_t:
                dict_t[t[index]] += 1
            else:
                dict_t[t[index]] = 1
                
        return dict_s == dict_t

Submission


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 2 - 49. Group Anagrams
下一篇
Day 4 - 347. Top K Frequent Elements
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言